<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入名称"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="角色状态"
          clearable
          style="width: 240px"
        >
          <el-option
            v-for="dict in dict.type.sys_normal_disable"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="所属分类" prop="pid">
        <treeselect
          v-model="queryParams.cateId"
          :options="cateOptions"
          :normalizer="normalizer"
          :show-count="true"
          placeholder="选择分类"
          style="width:180px;height: 32px;"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:group:create']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:group:update']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:group:delete']"
        >删除
        </el-button>
      </el-col>
      <!--      <el-col :span="1.5">-->
      <!--        <el-button-->
      <!--          type="warning"-->
      <!--          plain-->
      <!--          icon="el-icon-download"-->
      <!--          size="mini"-->
      <!--          @click="handleExport"-->
      <!--          v-hasPermi="['system:config:export']"-->
      <!--        >导出-->
      <!--        </el-button>-->
      <!--      </el-col>-->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="configList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="ID" align="center" width="60" prop="id"/>
      <el-table-column label="名称" align="center" prop="name" :show-overflow-tooltip="true"/>
      <el-table-column label="键名" align="center" prop="gkey" :show-overflow-tooltip="true"/>
      <el-table-column label="说明" align="center" prop="info" :show-overflow-tooltip="true"/>
      <el-table-column label="创建时间" align="center" prop="createdAt" width="180"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:group:update']"
          >修改
          </el-button>

          <el-button
            size="mini"
            type="text"
            icon="el-icon-setting"
            @click="handleSetValue(scope.row)"
            v-hasPermi="['system:group:data:lists']"
          >
            <router-link :to="'/system/group-data/index/' + scope.row.id" class="link-type">
              <span>数据列表</span>
            </router-link>
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:group:delete']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="90px">
        <el-form-item label="所属分类" prop="cateId">
          <treeselect
            v-model="form.cateId"
            :options="cateOptions"
            :normalizer="normalizer"
            :show-count="true"
            placeholder="选择分类"
            style="width:180px;height: 32px;"
          />
        </el-form-item>
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入名称"/>
        </el-form-item>
        <el-form-item label="键名" prop="gkey">
          <el-input v-model="form.gkey" placeholder="请输入键名"/>
        </el-form-item>
        <el-form-item label="说明" prop="info">
          <el-input v-model="form.info" placeholder="请输入键名"/>
        </el-form-item>

        <el-form-item label="字段" prop="fields">
          <el-button type="primary" size="mini" @click="addField()" v-if="form.fields && form.fields.length ==0"
                     icon="el-icon-circle-plus-outline" circle></el-button>
          <el-card class="box-card" v-for="(field, index) in form.fields" :key="index">
            <div slot="header" class="clearfix">
              <span>字段{{ index + 1 }}</span>
              <div style="float: right; padding: 3px 0">
                <el-button type="primary" size="mini" @click="addField()"
                           icon="el-icon-circle-plus-outline" circle></el-button>
                <el-button type="primary" size="mini" @click="delField(index)" icon="el-icon-remove-outline"
                           circle></el-button>
              </div>
            </div>
            <el-form-item label="配置类型" prop="type">
              <el-select
                v-model="field.type"
                placeholder="配置类型"
              >
                <el-option
                  v-for="dict in dict.type.sys_config_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="是否必填" prop="is_require">
              <el-radio-group v-model="field.is_require">
                <el-radio
                  v-for="dict in [{value:'1',label:'是'},{value:'0',label:'否'}]"
                  :key="dict.value"
                  :label="dict.value"
                >{{ dict.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="字段表单名" prop="field">
              <el-input v-model="field.field" placeholder="请输入字段表单名例：sex"/>
            </el-form-item>
            <el-form-item label="字段名称">
              <el-input v-model="field.name" placeholder="请输入字段名称例：姓别"/>
            </el-form-item>
            <el-form-item label="参数" prop="param">
              <el-input v-model="field.param" type="textarea"
                        placeholder="select,radio,checkbox等类型使用，value:label回车格式；或者输入框型的placeholder"/>
            </el-form-item>
          </el-card>
        </el-form-item>

        <el-form-item label="角色顺序" prop="sort">
          <el-input-number v-model="form.sort" controls-position="right" :min="0"/>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in dict.type.sys_normal_disable"
              :key="dict.value"
              :label="dict.value"
            >{{ dict.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  groupLists,
  groupView,
  groupCreate,
  groupDelete,
  groupUpdate
} from "@/api/system/group";
import {cateTree} from "@/api/system/cate";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "Config",
  components: {Treeselect},
  dicts: ['sys_config_type', 'sys_normal_disable'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      cateOptions: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 配置表格数据
      configList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 日期范围
      dateRange: [],
      // 查询配置
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: undefined,
        status: undefined,
        cateId: undefined,
      },
      // 表单配置
      form: {},
      // 表单校验
      rules: {
        cateId: [
          {required: true, message: "请选择分类", trigger: "blur"}
        ],
        name: [
          {required: true, message: "名称不能为空", trigger: "blur"}
        ],
        enName: [
          {required: true, message: "键名不能为空", trigger: "blur"}
        ],
        keyType: [
          {required: true, message: "配置类型不能为空", trigger: "blur"}
        ]
      },
      formValueRules: {
        value: [
          {required: true, message: "配置值不能为空", trigger: "blur"}
        ],
      },
      dialogValue: false,
      formValue: {},
      disabled: false,
    };
  },
  created() {
    this.getList()
    this.getTree()
  },
  methods: {
    closeValue() {
      this.dialogValue = false
    },
    resetValue() {
      this.form = {
        id: undefined,
        name: undefined,
        fields: [],
        cateId: 0,
        info: undefined,
        gkey: undefined,
        sort: 0,
        remark: undefined,
        status: '0',
      };
      this.resetForm("form")
    },
    handleSetValue(row) {
      this.title = `${row.name} 配置值`
      this.resetValue()
      groupView(row.id).then(response => {
        this.dialogValue = true
        this.formValue.id = row.id
        this.formValue.value = response.data.value
        this.formValue.keyType = response.data.keyType
        this.formValue.name = response.data.name
        this.formValue.rule = response.data.rule
        this.formValue.ruleArr = response.data.ruleArr
      });
    },
    handelSaveValue() {
      this.$refs["formValue"].validate(valid => {
        if (valid) {
          setConfigValue({id: this.formValue.id, value: this.formValue.value}).then(response => {
            this.$modal.msgSuccess("配置值修改成功");
            this.dialogValue = false;
            this.getList();
          });
        }
      });
    },
    getTree() {
      cateTree({type: '03'}).then(response => {
        const tree = response.data;
        tree.splice(0, 0, {id: 0, label: '主类目', children: []})
        this.cateOptions = tree
      })
    },
    /** 查询配置列表 */
    getList() {
      this.loading = true;
      groupLists(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
          this.configList = response.data.list;
          this.total = response.data.count;
          this.loading = false;
        }
      );
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.resetValue();
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加配置";
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length != 1
      this.multiple = !selection.length
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      groupView(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改配置";
      });
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != undefined) {
            groupUpdate(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            groupCreate(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除配置编号为"' + ids + '"的数据项？').then(function () {
        return groupDelete(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/config/export', {
        ...this.queryParams
      }, `config_${new Date().getTime()}.xlsx`)
    },
    /** 刷新缓存按钮操作 */
    handleRefreshCache() {
      refreshCache().then(() => {
        this.$modal.msgSuccess("刷新成功");
      });
    },
    delField(index) {
      this.form.fields.splice(index, 1)
    },
    addField() {
      this.form.fields.push(this.getFieldForm())
    },
    getFieldForm() {
      return {
        type: undefined,
        is_require: "0",
        param: '',
        field: undefined,
        name: undefined,
      }
    },
    /** 转换菜单数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.label,
        children: node.children
      };
    },
    subsave(value) {
      console.log(value)
      this.form.value = JSON.stringify(value)
    },
  }
};
</script>
